//-------------------------------------------------------------------------------------
// <copyright file="Host.cs" company="Microsoft">
//      Copyright (c) 2003 Microsoft Corporation. All rights reserved.
//      THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
//      EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
//      WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
// <summary>
//      Represents a logical set of zero or more runtime processes in which services, pipelines, and other items are deployed.
// </summary>  
//-------------------------------------------------------------------------------------

namespace Microsoft.Sdc.Tasks.BizTalk2004.Configuration
{

	#region Using directives 
    
	using System;
    using System.Xml.Serialization;
    using System.Management;
	
	#endregion 

    /// <summary>
	/// Represents a logical set of zero or more runtime processes in which services, pipelines, and other items are deployed.
    /// </summary>
	internal sealed class Host : BizTalkConfigurableEntityBase
	{

		#region Member Variables 

		private bool isDefault;
		private string ntGroupName;
		private HostType hostType;

		private bool hostTracking;
		private bool authTrusted;


		#endregion 

		#region properties 
	
		/// <summary>
		/// Denotes a default host.
		/// </summary>
		/// <value>boolean; true if the Host is a default host, false if otherwise.</value>
		public bool IsDefault
		{
			get {return this.isDefault;}
		}

		/// <summary>
		/// Gets the Windows NT group name of the host.
		/// </summary>
		/// <value>a string representing the NT group name of the host.</value>
		public string NTGroupName
		{
			get { return this.ntGroupName; }
		}

		/// <summary>
		/// Gets the host type
		/// </summary>
		/// <value>A <see cref="Microsoft.Sdc.Tasks.BizTalk2004.Configuration.HostType"/> enumeration containing the type of the host.</value>
		public HostType HostType
		{
			get { return this.hostType; }
		}

		/// <summary>
		/// Gets or sets the the HostTracking attribute
		/// </summary>
		public bool HostTracking
		{
			get {return this.hostTracking;}
			set {this.hostTracking = value;}
		}

		/// <summary>
		/// Gets or sets the AuthTrusted Attribute
		/// </summary>
		public bool AuthTrusted
		{
			get {return this.authTrusted;}
			set {this.authTrusted = value;}
		}





		#endregion 

		#region methods

		/// <summary>
		/// Creates a new Host Instance. This is private because instance of this class can only be created with
		/// the Load method
		/// </summary>
		/// <param name="installation">The <see cref="Microsoft.Sdc.Tasks.BizTalk2004.Configuration.BizTalkInstallation"/> object of this host.</param>
		/// <param name="name">The name of this host.</param>
		private Host(BizTalkInstallation installation, string name): base(installation, name){}

		/// <summary>
		/// Loads the details of a  host 
		/// </summary>
		/// <param name="installation">The <see cref="Microsoft.Sdc.Tasks.BizTalk2004.Configuration.BizTalkInstallation"/> object of this host.</param>
		/// <param name="name">The name of this host.</param>
		public static Host Load(BizTalkInstallation installation, string name)
		{
			//check inputs
			if (installation == null) throw new ArgumentException("installation");
			if (name == null || name.Length == 0) throw new ArgumentException("name");

			//loading native type
			BtsHost btsHost = installation.CatalogExplorer.Hosts[name];

			Host host = null;
			if (btsHost != null)
			{
				host = new Host(installation, btsHost.Name);
				host.isDefault = btsHost.IsDefault;
				host.ntGroupName = btsHost.NTGroupName;
				host.hostType = (HostType)Enum.Parse(typeof(HostType), ((int)btsHost.Type).ToString());

				//loading the Wmi Properties
				ManagementObject btsHostSetting = ManagementHelper.GetHostSettingObject(installation, host.Name);
				host.hostTracking = (bool) btsHostSetting.GetPropertyValue("HostTracking");
				host.authTrusted =  (bool) btsHostSetting.GetPropertyValue("AuthTrusted");
			}

			return host;
		}


		/// <summary>
		/// Checks if the Host exists within BizTalk
		/// </summary>
		/// <param name="installation">
		/// The Microsoft.Sdc.Tasks.Configuration.BizTalk.Installation to search in.
		/// </param>
		/// <param name="name">
		/// The name of the Host
		/// </param>
		/// <returns>
		/// <b>true</b> if the Host exists, or <b>false</b> otherwise.
		/// </returns>
		public static bool Exists(BizTalkInstallation installation, string name)
		{
			return BizTalkEntityBase.Exists(installation, CollectionType.Host, name);
		}

	
		#endregion

		#region WMI methods


		/// <summary>
		/// saves this object
		/// </summary>
		protected internal override void SaveImpl()
		{
			//creating WMI objects 
			ManagementObject btsHostSetting = ManagementHelper.GetHostSettingObject(this.Installation, this.Name);

			//setting the properties
			if (this.hostType == HostType.InProcess)
			{
				btsHostSetting.SetPropertyValue("HostTracking", this.hostTracking);
				btsHostSetting.SetPropertyValue("IsDefault", this.isDefault);
			}

			btsHostSetting.SetPropertyValue("NTGroupName", this.ntGroupName);
			btsHostSetting.SetPropertyValue("AuthTrusted", this.authTrusted);
			btsHostSetting.Put();

		}

		/// <summary>
		/// Starts all BizTalk Host instances for the given BizTalk Host.
		/// </summary>
		public void Start()
		{
			// Call the start method on the underlying management object
			ManagementHelper.GetHostObject(this.Installation, this.Name).InvokeMethod("Start", null, null);
		}


		/// <summary>
		/// Stops all BizTalk Host instances for the given BizTalk Host.
		/// </summary>
		public void Stop()
		{
			// Call the stop method on the underlying management object
			ManagementHelper.GetHostObject(this.Installation, this.Name).InvokeMethod("Stop", null, null);
		}


		/// <summary>
		/// Creates a new host, and maps it to a server
		/// </summary>
		/// <param name="installation"></param>
		/// <param name="hostname"></param>
		/// <param name="hostType"></param>
		/// <param name="groupName"></param>
		/// <param name="trusted"></param>
		/// <param name="serverName"></param>
		/// <param name="username"></param>
		/// <param name="password"></param>
		/// <param name="hostTracking"></param>
		/// <param name="isDefault"></param>
		public static void CreateInstance(BizTalkInstallation installation, string hostname, HostType hostType, 
			string groupName, bool trusted, string serverName, string username, string password,
			bool hostTracking, bool isDefault)
		{
			try
			{
				PutOptions options = new PutOptions(); 
				options.Type = PutType.CreateOnly;

				ManagementClass hostSettingClass = ManagementHelper.GetHostSettingClass(installation);
				ManagementObject btsHostSetting =  hostSettingClass.CreateInstance();

				//ManagementClass objHostSettingClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_HostSetting", null);
				//ManagementObject btsHostSetting  = objHostSettingClass.CreateInstance();

				//set the properties for the Managementobject
				btsHostSetting["Name"] = hostname;
				btsHostSetting["HostType"] = (int)hostType;
				btsHostSetting["NTGroupName"] = groupName;
				btsHostSetting["AuthTrusted"] = trusted;
				if (hostType == HostType.InProcess)
				{
					btsHostSetting.SetPropertyValue("HostTracking", hostTracking);
					btsHostSetting.SetPropertyValue("IsDefault", isDefault);
				}
            
				//create the Managementobject
				btsHostSetting.Put(options);

				ManagementClass btsServerHostClass = ManagementHelper.GetServerHostClass(installation);
				ManagementObject serverHostObject = btsServerHostClass.CreateInstance();
				serverHostObject["ServerName"] = serverName;
				serverHostObject["HostName"] = hostname;

				//Invoke the Map method of the ServerHost instance
				serverHostObject.InvokeMethod("Map",null);


				ManagementClass btsHostInstanceClass = ManagementHelper.GetHostInstanceClass(installation);
				ManagementObject hostInstanceObject = btsHostInstanceClass.CreateInstance();
				hostInstanceObject["Name"] = string.Format("Microsoft BizTalk Server {0} {1}", hostname, serverName);

				object[] args = new object[2] {username, password};
				hostInstanceObject.InvokeMethod("Install", args);
			}
			catch(Exception excep)
			{
				System.Diagnostics.Trace.WriteLine("CreateHost - " + hostname + " - failed: " + excep.Message);
				throw;
			}
		}

		/// <summary>
		/// Deletes a host instance
		/// </summary>
		/// <param name="installation"></param>
		/// <param name="name"></param>
		public static void Delete(BizTalkInstallation installation, string name)
		{
			try
			{
				ManagementObject objHostSetting = ManagementHelper.GetHostSettingObject(installation, name);

				//delete the Managementobject
				objHostSetting.Delete();
			}
			catch (Exception ex)
			{
				System.Diagnostics.Trace.WriteLine(string.Format("DeleteHost - {0} - failed: {1}", name, ex.ToString()));
			}
		}
		#endregion
	}
}

